import * as http from "http";
import * as querystring from "querystring";
import * as _ from "lodash";

/**
 * 导入数据
 * @param dataJson 数据
 * @param serviceUrl 服务地址
 * @param token token
 */
function importData(dataJson, serviceUrl, token) {
  //http请求地址
  const url = _.trimEnd(serviceUrl,'/') + "/api/open/import_data";
  //http请求参数
  const data = querystring.stringify({
    token: token,
    type: 'swagger',
    json: JSON.stringify(dataJson),
    merge: 'good'
  });
  const options = {
    port: 80, // 请求的目标端口号
    method: 'POST', // 请求方法
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': Buffer.byteLength(data)
    }
  };

  const request = http.request(url, options, (res) => {
    let responseData = '';

    res.on('data', (data) => {
      responseData += data.toString();
    });
    res.on('end', () => {
      console.log(responseData);
    });
  });
  request.write(data);
  request.end();
}

/**
 * 本地文件信息导入
 * @param dataJson
 */
function localFileConfigImportData(dataJson:any, configJson:any) {
  if (!configJson.enable) {
    console.log('未启用远程导入');
    return ;
  }
  //导入数据
  importData(dataJson, configJson.serviceUrl, configJson.token);
}

export {importData,localFileConfigImportData};
